package com.csj.mvvm.utils

import android.content.ContentResolver
import android.content.ContentValues
import android.graphics.Bitmap
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import com.csj.mvvm.App
import java.io.*
import java.net.HttpURLConnection
import java.net.URL
import kotlin.concurrent.thread


object StorageUtil {
    /**
     * 使用MediaStore创建文件（下载）
     */
    fun addBitmapToAlbum(
        bitmap: Bitmap,
        fileName: String,
        mimeType: String,
        compressFormat: Bitmap.CompressFormat
    ) {
        try {
            val values = ContentValues()
            values.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
            values.put(MediaStore.MediaColumns.MIME_TYPE, mimeType)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM)
            } else {
                val galleryPath: String =
                    (Environment.getExternalStorageDirectory().path + File.separator + Environment.DIRECTORY_DCIM
                            + File.separator.toString() + "Camera" + File.separator)
                values.put(MediaStore.MediaColumns.DATA, galleryPath + fileName)
//                values.put(MediaStore.MediaColumns.DATA, "${Environment.getExternalStorageDirectory().path}/${Environment.DIRECTORY_DCIM}/$fileName")
            }
            val contentResolver: ContentResolver = App.instance.contentResolver
            val uri = contentResolver.insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                values
            ) //content://media/external/images/media
            if (uri != null) {
                val outputStream = contentResolver.openOutputStream(uri)
                if (outputStream != null) {
                    bitmap.compress(compressFormat, 100, outputStream)
                    outputStream.close()
                }
                ToastUtil.showToast("图片保存成功")
            }
        } catch (e: Exception) {
        }
    }

    fun downloadFile(fileUrl: String, fileName: String) {
        thread {
            try {
                val url = URL(fileUrl)
                val connection = url.openConnection() as HttpURLConnection
                connection.requestMethod = "GET"
                connection.connectTimeout = 10000
                connection.readTimeout = 10000
                val inputStream = connection.inputStream
                val bis = BufferedInputStream(inputStream)
                var outputStream: OutputStream?
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    val values = ContentValues()
                    values.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
                    values.put(
                        MediaStore.MediaColumns.RELATIVE_PATH,
                        Environment.DIRECTORY_DOWNLOADS
                    )
                    val uri = App.instance.contentResolver.insert(
                        MediaStore.Downloads.EXTERNAL_CONTENT_URI,
                        values
                    )
                    outputStream = App.instance.contentResolver.openOutputStream(uri!!)

                } else {
                    val apkFile = File(
                        App.instance.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS),
                        fileName
                    )
                    if (apkFile.exists()) {
                        apkFile.delete()
                    }
                    outputStream = FileOutputStream(apkFile)
                }
                if (outputStream != null) {
                    val bos = BufferedOutputStream(outputStream)
                    val buffer = ByteArray(10 * 1024)
                    var bytes = bis.read(buffer)
                    while (bytes >= 0) {
                        bos.write(buffer, 0, bytes)
                        bos.flush()
                        bytes = bis.read(buffer)
                    }
                    bos.close()
                    AppManager.instance.currentActivity()!!.runOnUiThread {
                        ToastUtil.showToast("$fileName 下载成功！")
                    }
                }
                bis.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}